#import "JudgeViewController.h"
#import "BaseHiddenTabBarController.h"
#import "JudgeManager.h"
#import "ASIHTTPRequest.h"
#import "SBJsonParser.h"
#import "MBProgressHUD.h"
#import "RegisterViewController.h"
#import "LoginViewController.h"
#import "UserManager.h"
#import "MenuViewController.h"
#import "CMActionSheet.h"

static const int mainviewPlusHeight = 80;
static const int judgeactionMinusHeight = 30;


@implementation JudgeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        //
    }
    return self;
}

- (void)dealloc
{
    PP_RELEASE(hudLoading);
    PP_RELEASE(mainView);
    PP_RELEASE(judgText);
    PP_RELEASE(judgeImg);
    PP_RELEASE(judgeWebView);
    PP_RELEASE(nomore);
    PP_RELEASE(loadingGif);
    PP_RELEASE(loadingImg);
    PP_RELEASE(goodBtn);
    PP_RELEASE(badBtn);
    PP_RELEASE(warnBtn);
    PP_RELEASE(passBtn);
    PP_RELEASE(judgeDoneView);
    PP_RELEASE(contentJudgeBg);
    PP_RELEASE(judgeTime);
    PP_RELEASE(refreshBtn);
    PP_RELEASE(judgeManager);
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.viewDeckController.centerhiddenInteractivity = IIViewDeckCenterHiddenNotUserInteractiveWithTapToClose;
    self.navigationController.navigationBar.backgroundColor =[UIColor clearColor]; //导航上那条黑线的原因在这里
    baseTitle.text = @"审个帖";

    //菜单按钮
    UIButton* menuBtn= [[[UIButton alloc] initWithFrame:CGRectMake(0.0, 0.0, 44.0, 44.0)] autorelease];
    [menuBtn setBackgroundImage:[UIImage imageNamed:@"nav_bar_menu_1.png"] forState:UIControlStateNormal];
    [menuBtn setBackgroundImage:[UIImage imageNamed:@"nav_bar_menu_2.png"] forState:UIControlStateHighlighted];
    [menuBtn addTarget:self action:@selector(showMenu) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *menuBarBtn = [[[UIBarButtonItem alloc] initWithCustomView:menuBtn] autorelease];
    [self.navigationItem setLeftBarButtonItem:menuBarBtn];

    refreshBtn= [[[UIButton alloc] initWithFrame:CGRectMake(0.0, 0.0, 44.0, 44.0)] autorelease];
    [refreshBtn setBackgroundImage:[UIImage imageNamed:@"action_judfe_refresh_1.png"] forState:UIControlStateNormal];
    [refreshBtn setBackgroundImage:[UIImage imageNamed:@"action_judfe_refresh_2.png"] forState:UIControlStateHighlighted];
    [refreshBtn addTarget:self action:@selector(refreshJudgeData) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *refreshBarBtn = [[[UIBarButtonItem alloc] initWithCustomView:refreshBtn] autorelease];
    [self.navigationItem setRightBarButtonItem:refreshBarBtn];
    refreshBtn.hidden = YES;
    
    [goodBtn addTarget:self action:@selector(judgeFunny) forControlEvents:UIControlEventTouchUpInside];
    [badBtn addTarget:self action:@selector(judgeUnfunny) forControlEvents:UIControlEventTouchUpInside];
    [warnBtn addTarget:self action:@selector(judgeWarn) forControlEvents:UIControlEventTouchUpInside];
    [passBtn addTarget:self action:@selector(judgePass) forControlEvents:UIControlEventTouchUpInside];
    
    if ([[UserManager sharedInstance]isLogin] ) {
        loadingImg = nil;
        loadingGif = nil;
        hudLoading = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hudLoading.labelText = @"正在加载...";
        hudLoading.opacity = PP_mbprogressHudOpacity;
    }
}

- (void)viewDidUnload
{
    PP_RELEASE(hudLoading);
    PP_RELEASE(mainView);
    PP_RELEASE(judgText);
    PP_RELEASE(judgeImg);
    PP_RELEASE(judgeWebView);
    PP_RELEASE(nomore);
    PP_RELEASE(loadingGif);
    PP_RELEASE(loadingImg);
    PP_RELEASE(goodBtn);
    PP_RELEASE(badBtn);
    PP_RELEASE(warnBtn);
    PP_RELEASE(passBtn);
    PP_RELEASE(judgeDoneView);
    PP_RELEASE(contentJudgeBg);
    PP_RELEASE(judgeTime);
    PP_RELEASE(refreshBtn);
    PP_RELEASE(judgeManager);
    [super viewDidUnload];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    if( ![[UserManager sharedInstance] isLogin]){
        Log(@"not login yet");
        [self baseShowLoginSheet];
        return;
    }
    
    judgeManager = [[JudgeManager alloc]init];
    
    [self setStateInit];
    [self setStateLoading];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [judgeManager httpPreload:5];
        Log(@"listJudge count: %d",judgeManager.listJudge.count);
        dispatch_async(dispatch_get_main_queue(), ^{
            [self setStateLoaded];
            //无数据
            if (judgeManager.listJudge.count==0) {
                [self setStateFinish];
                Log(@"setStateFinish");
                //有数据
            }else{
                [self setStateStart];
                Log(@"setStateStart");
                JudgeModel *tjudge = [judgeManager.listJudge objectAtIndex:0];
                [self showJudgeWithId:tjudge.judgeId withText:tjudge.judgeText withImg:tjudge.judgeImgUrl withTime:tjudge.judgeTime];
            }
        });
    });
}

- (void)findMisbehavingScrollViews
{
    UIView *view = [[UIApplication sharedApplication] keyWindow];
    [self findMisbehavingScrollViewsIn:view];
}

- (void)findMisbehavingScrollViewsIn:(UIView *)view
{
    if ([view isKindOfClass:[UIScrollView class]])
    {
        NSLog(@"Found UIScrollView: %@", view);
        if ([(UIScrollView *)view scrollsToTop])
        {
            NSLog(@"scrollsToTop = YES!");
            [(UIScrollView *)view setScrollsToTop:NO];
        }
    }
    for (UIView *subview in [view subviews])
    {
        [self findMisbehavingScrollViewsIn:subview];
    }
}

- (void)refreshJudgeData{
    if( ![[UserManager sharedInstance] isLogin]){
        Log(@"not login yet");
        [self baseShowLoginSheet];
        return;
    }
    
    judgeManager = [[JudgeManager alloc]init];
    
    [self setStateInit];
    [self setStateLoading];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [judgeManager httpPreload:5];
        Log(@"listJudge count: %d",judgeManager.listJudge.count);
        dispatch_async(dispatch_get_main_queue(), ^{
            //无数据
            if (judgeManager.listJudge.count==0) {
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    sleep(1);
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self setStateLoaded];
                        [self setStateFinish];
                        Log(@"setStateFinish");
                    });
                });
            //有数据
            }else{
                [self setStateLoaded];
                [self setStateStart];
                Log(@"setStateStart");
                JudgeModel *tjudge = [judgeManager.listJudge objectAtIndex:0];
                [self showJudgeWithId:tjudge.judgeId withText:tjudge.judgeText withImg:tjudge.judgeImgUrl withTime:tjudge.judgeTime];
            }
        });
    });
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)showJudgeWithId:(NSInteger)judgeId withText:(NSString *)text withImg:(NSString *)imgUrl withTime:(NSString *)time
{
    judgeTime.text = [NSString stringWithFormat:@"发表时间:%@", time];
    judgText.text = text;
    CGRect textFrame = judgText.frame;
    textFrame.size.height = judgText.contentSize.height;
    judgText.frame = textFrame;
    UIImage *contentViewBg = [[UIImage imageNamed:@"post_input.png"] stretchableImageWithLeftCapWidth:1 topCapHeight:1];

    if( [imgUrl length]>0 ){
        [self setStateLoading];
        judgeImg.frame = CGRectMake((mainView.frame.size.width-120)/2,judgText.frame.origin.y+judgText.frame.size.height,120,120);
        judgeImg.image = [UIImage imageNamed:@"default_photo.png"];
        judgeImg.hidden = NO;
        judgeWebView.frame = CGRectZero;
        judgeWebView.hidden = YES;
        judgeWebView.userInteractionEnabled = NO;
        CGSize mainSize = mainView.contentSize;
        mainSize.height = judgText.frame.size.height + judgeImg.frame.size.height+ mainviewPlusHeight;
        [mainView setContentSize:mainSize];
        
        contentJudgeBg.frame = CGRectMake(contentJudgeBg.frame.origin.x, contentJudgeBg.frame.origin.y, contentJudgeBg.frame.size.width, mainSize.height -judgeactionMinusHeight);
        contentJudgeBg.image = contentViewBg;
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//            Log(@"getting %@",imgUrl);
            NSData *imgData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:imgUrl]];
            if(loadingImg!=nil){
                [loadingImg release]; loadingImg = nil;
            }
            if( loadingGif!=nil ){
                [loadingGif release]; loadingGif = nil;
            }
            loadingImg = [[UIImage alloc] initWithData:imgData];
            if([[imgUrl lowercaseString] hasSuffix:@"gif"]){
                loadingGif = imgData;
            }else{
                [imgData release];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                Log(@"showing");
                CGRect imgFrame;
                if (loadingImg.size.width < 280) {
                    imgFrame = CGRectMake(20,judgText.frame.origin.y+judgText.frame.size.height,loadingImg.size.width,loadingImg.size.height);
                }else{
                    imgFrame = CGRectMake(20,judgText.frame.origin.y+judgText.frame.size.height,280,280*loadingImg.size.height/loadingImg.size.width);
                }
                if( loadingGif != nil ){
                    judgeWebView.frame = imgFrame;
                    [judgeWebView loadData:loadingGif MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];
                    judgeWebView.hidden = NO;
                    judgeImg.frame = CGRectZero;
                    judgeImg.hidden = YES;
                }else{
                    judgeImg.frame = imgFrame;
                    judgeImg.image = loadingImg;
                    judgeImg.hidden = NO;
                    judgeWebView.frame = CGRectZero;
                    judgeWebView.hidden = YES;
                }
                CGSize mainSize = mainView.contentSize;
                mainSize.height = judgText.frame.size.height + judgeImg.frame.size.height + judgeWebView.frame.size.height+mainviewPlusHeight;
                [mainView setContentSize:mainSize];
                contentJudgeBg.frame = CGRectMake(contentJudgeBg.frame.origin.x, contentJudgeBg.frame.origin.y, contentJudgeBg.frame.size.width, mainSize.height-judgeactionMinusHeight );
                contentJudgeBg.image = contentViewBg;
                [self setStateLoaded];
            });
        });
    }else{
        judgeImg.frame = CGRectZero;
        judgeImg.hidden = YES;
        judgeWebView.frame = CGRectZero;
        judgeWebView.hidden = YES;
        Log(@"no img");
        CGSize mainSize = mainView.contentSize;
        mainSize.height = judgText.frame.size.height+mainviewPlusHeight;
        [mainView setContentSize:mainSize];

        contentJudgeBg.frame = CGRectMake(contentJudgeBg.frame.origin.x, contentJudgeBg.frame.origin.y, contentJudgeBg.frame.size.width, mainSize.height -judgeactionMinusHeight);
        contentJudgeBg.image = contentViewBg;
    }
    
    
    [self findMisbehavingScrollViews];
    mainView.scrollsToTop = YES;
}

//异步获取下一张图片公用的方法
-(void)nextJudgeJoke:(int)actionMark opinion:(NSString *)pOpinion
{    
    if([judgeManager.listJudge count] != 0){
        //减去listJudge中第一个
        JudgeModel *tjudge = [judgeManager.listJudge objectAtIndex:0];
        int judgeId = tjudge.judgeId;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            switch (actionMark) {
                case 1:
                {
                    [judgeManager httpJudge:judgeId opinion:@"laugh" content:nil];
                    break;
                }
                case 2:
                {
                    [judgeManager httpJudge:judgeId opinion:@"unlaugh" content:nil];
                    break;
                }
                case 3:
                    break;
                default:
                {
                    [judgeManager httpJudge:judgeId opinion:pOpinion content:@"from_ios_client"];
                    break;
                }
            }
        });
        
        [judgeManager.listJudge removeObjectAtIndex:0];
        if([judgeManager.listJudge count] != 0){
            JudgeModel *tjudge = [judgeManager.listJudge objectAtIndex:0];
            Log(@"showing: %d",tjudge.judgeId);
            [self showJudgeWithId:tjudge.judgeId withText:tjudge.judgeText withImg:tjudge.judgeImgUrl withTime:tjudge.judgeTime];
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                //然后请求追加一个
                JudgeModel *nextJudgejoke = [judgeManager.listJudge objectAtIndex:judgeManager.listJudge.count-1];
                [judgeManager httpLoadNextFrom:nextJudgejoke.judgeId];
                Log(@"listJudge count: %d",judgeManager.listJudge.count);
            });
        }else{
            ////不追加
            [self setStateFinish];
            refreshBtn.hidden = NO;
        }
    }else{
        ////不审核
    }
}

-(void)setStateInit
{
    mainView.hidden = YES;
    nomore.hidden = YES;
    judgeDoneView.hidden = YES;
    refreshBtn.hidden = YES;
    judgeActionView.hidden = NO;
}

-(void)setStateStart
{
    mainView.hidden = NO;
    nomore.hidden = YES;
    judgeDoneView.hidden = YES;
    refreshBtn.hidden = YES;
    judgeActionView.hidden = NO;
}

-(void)setStateFinish
{
    mainView.hidden = YES;
    nomore.hidden = NO;
    judgeDoneView.hidden = NO;
    judgeActionView.hidden = YES;
    refreshBtn.hidden = NO;
}

-(void)setStateLoading
{
    isLoadingFinish = NO;
    hudLoading.hidden = NO;
}

-(void)setStateLoaded
{
    isLoadingFinish = YES;
    hudLoading.hidden = YES;
    refreshBtn.hidden = YES;
}

//loading=yes并且 netIsError = no才执行
-(void)judgeFunny {
    if (!isLoadingFinish){
        return;
    }
    
    //+1动画
    UIImageView * plusOne = [[UIImageView alloc] initWithFrame:CGRectMake(goodBtn.frame.origin.x+12,self.view.frame.size.height-goodBtn.frame.size.height, 24 , 24)];
    plusOne.image = [UIImage imageNamed:@"plus.png"];
    plusOne.backgroundColor = [UIColor clearColor];
    plusOne.alpha = 1.0f;
    plusOne.hidden = YES;
    [self.view addSubview:plusOne];

    plusOne.hidden = NO;
    [UIView animateWithDuration:1.0 animations:^{
        plusOne.alpha = 0.0f;
        plusOne.frame = CGRectMake(goodBtn.frame.origin.x + 12,self.view.frame.size.height-goodBtn.frame.size.height-80, 48, 48);
    }completion:^(BOOL finished) {
        [plusOne removeFromSuperview];
        [plusOne release];
    }];
    Log(@"judgeFunny");
    [self nextJudgeJoke:1 opinion:@"laugh"];
}

-(void)judgeUnfunny {
    if (!isLoadingFinish){
        return;
    }
     UIImageView * minusOne = [[UIImageView alloc] initWithFrame:CGRectMake(badBtn.frame.origin.x +12,self.view.frame.size.height-badBtn.frame.size.height, 24 , 24)];
    
    minusOne.image = [UIImage imageNamed:@"minus.png"];
    minusOne.backgroundColor = [UIColor clearColor];
    minusOne.alpha = 1.0f;
    minusOne.hidden = YES;
    [self.view addSubview:minusOne];
    minusOne.hidden = NO;
    [UIView animateWithDuration:1.0 animations:^{
        minusOne.alpha = 0.0f;
        minusOne.frame = CGRectMake(badBtn.frame.origin.x +12,self.view.frame.size.height-badBtn.frame.size.height-80, 48, 48);
    }completion:^(BOOL finished) {
        [minusOne removeFromSuperview];
        [minusOne release];
    }];
    Log(@"judgeUnfunny");
    [self nextJudgeJoke:2 opinion:@"unlaugh"];
}

-(void)judgePass {
    if (!isLoadingFinish){
        return;
    }
    Log(@"judgeSkip");
    [self nextJudgeJoke:3 opinion:nil];
}                                                                                                     

-(void)judgeWarn{
    if (!isLoadingFinish){
        return;
    }
    Log(@"judgeReport");
//
    CMActionSheet *actionSheet = [[[CMActionSheet alloc] init] autorelease];
    [actionSheet addButtonWithTitle:@"政治敏感内容" type:CMActionSheetButtonTypeFreedom block:^{
        [self nextJudgeJoke:4 opinion:@"政治敏感内容"];
    }];
    
    [actionSheet addSeparator];
    [actionSheet addButtonWithTitle:@"色情低俗信息" type:CMActionSheetButtonTypeFreedom block:^{
        [self nextJudgeJoke:4 opinion:@"色情低俗信息"];

    }];
    [actionSheet addSeparator];
    [actionSheet addButtonWithTitle:@"乱发广告" type:CMActionSheetButtonTypeFreedom block:^{
        [self nextJudgeJoke:4 opinion:@"乱发广告"];
    }];
    [actionSheet addSeparator];
    [actionSheet addButtonWithTitle:@"其他" type:CMActionSheetButtonTypeFreedom block:^{
        [self nextJudgeJoke:4 opinion:@"其他"];
    }];
    [actionSheet addSeparator];
    [actionSheet addButtonWithTitle:@"取消" type:CMActionSheetButtonTypeFreedom block:^{
        
    }];
    [actionSheet present];
    
//    [self baseShowHUD:@"已举报" atY:0.0];
}

- (void)back{
    BaseHiddenTabBarController *tTabBarController = (BaseHiddenTabBarController *)self.tabBarController;
    [tTabBarController select:0];
}

//- (void)showSheet
//{
//    Log(@"showSheet");
//    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"审帖需要先登录哟！"
//                                                             delegate:self
//                                                    cancelButtonTitle:@"取消"
//                                               destructiveButtonTitle:nil
//                                                    otherButtonTitles:@"注册", @"登录", nil];
//    [actionSheet showInView:self.view];
//    [actionSheet release];
//}
//
//- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
//    Log(@"actionSheet buttonIndex:%i", buttonIndex);
//    if (buttonIndex == actionSheet.cancelButtonIndex) {
//        [self back];
//        return;
//    }
//    switch (buttonIndex) {
//        case 0: {
//            Log(@"actionSheet navigationController is nil ?%@",self.navigationController);
//            RegisterViewController *RegisterController = [[RegisterViewController alloc]initWithNibName:@"RegisterViewController" bundle:nil];
//            [self.navigationController pushViewController:RegisterController animated:YES];
//            break;
//        }
//        case 1: {
//            LoginViewController *LoginController = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
//            [self.navigationController pushViewController:LoginController animated:YES];
//            break;
//        }
//    }
//}
//
- (void)showMenu {
    [self.viewDeckController toggleLeftView];
}


@end